package com.yesallchina.wxapp.officialaccount.bean;

import com.yesallchina.wxapp.officialaccount.utils.JacksonUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于在RestFul请求当中规范响应的结果数据格式，使得结果可以被以统一的风格进行处理
 *
 */
public final class ResponseDTO implements Serializable {

    public final static int SUCCESS = 200;
    public final static int ERROR = 500;
    public final static int NO_LOGIN = 10000;

    public final static String renderSuccess(Object data){
        return renderSuccess(data,null);
    }

    public final static String renderSuccess(Object data,String msg){
        if (!StringUtils.hasText(msg)) {
            msg = "操作成功";
        }
        return JacksonUtils.generate(createResponseBody(SUCCESS,msg,data));
    }

    public final static String renderSuccess(){
        return renderSuccess(null,"");
    }

    public final static String renderError(String msg){
        if (!StringUtils.hasText(msg)) {
            msg = "操作出现错误";
        }
        return JacksonUtils.generate(createResponseBody(ERROR,msg,null));
    }

    public final static String renderNoLogin(){
        String msg = "当前会话失败，请先登录";
        return JacksonUtils.generate(createResponseBody(NO_LOGIN,msg,null));
    }

    private final static Map createResponseBody(int code,String msg,Object data){
        return new HashMap() {{
            put("code", code);
            put("msg", msg);
            put("data", data);
        }};
    }
}
